package com.bwie.parkdemo.mvvm.viewmodel;

import android.app.Application;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.TimeUtils;
import com.bwie.lib_core.base.BaseEntity;
import com.bwie.lib_core.mvvm.base.BaseViewModel;
import com.bwie.parkdemo.adapter.CarImgAdapter;
import com.bwie.parkdemo.adapter.ColorAdapter;
import com.bwie.parkdemo.mvvm.model.ApplyParkingModel;
import com.bwie.parkdemo.mvvm.model.entity.AddSysParkingEntity;
import com.bwie.parkdemo.mvvm.model.entity.CarColorEntity;
import com.bwie.parkdemo.mvvm.model.entity.CarEntity;
import com.bwie.parkdemo.mvvm.model.entity.CarImgEntity;
import com.bwie.parkdemo.mvvm.model.entity.LoginEntity;
import com.bwie.parkdemo.mvvm.model.entity.UploadImgsEntity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 我的车位申请界面
 * */
public class ApplyParkingViewModel extends BaseViewModel<ApplyParkingModel> {

    public ObservableField<String> timeStr;//车位使用的时间
    public ObservableField<String> applyTimeStr;//车位申请时间
    public ObservableField<String> nameStr;//用户名
    public ObservableField<String> departmentStr;//部门
    public ObservableField<String> carNumStr = new ObservableField<>("京A8888");//车牌照
    public ObservableField<String> colorStr;//车辆颜色值
    private LoginEntity.Values userEntity;//用户详情
    private String startStr = "开始时间";
    private String endStr = "结束时间";
    //colorrecyclerview需要使用的数据
    public ApplyParkingItemListener listener;//颜色列表item点击监听器
    //界面中按钮点击事件
    public ClickListener clickListener = new ClickListener();
    public int colorType = 1;
    public int imgType = 2;
    private ArrayList<Object> imgs = new ArrayList<>();//图片本地路径集合与图片recyclerview绑定
    public ObservableField<ArrayList<Object>>colorDatas;
    public ObservableField<ArrayList<Object>>imgDatas;//保存全部拍照后的图片路径集合
    private List<String>serverImgs;//服务器上，上传后的图片链接地址
    private List<String>pathes = new ArrayList<>();
    private int selColorId = 0;
    public int parkId = 47;
    private int carId = 0;
    private String parkName;
    public boolean resultFlag = false;//来访预约界面进入标志

    public ApplyParkingViewModel(@NonNull Application application) {
        super(application);
        //初始化创建color rv 相关的数据源
        listener = new ApplyParkingItemListener();
        colorDatas = new ObservableField<>();
        imgs.add("+");//添加默认添加数据
        imgDatas = new ObservableField<>(imgs);
    }

    @Override
    protected ApplyParkingModel createModel() {
        return new ApplyParkingModel();
    }


    public void setParkName(String parkName) {
        this.parkName = parkName;
    }

    @Override
    protected void initData() {
        //初始化获取用户信息
        userEntity = m.requstUser(getApplication());
        //初始化获取车辆颜色
        requestColor();
        //初始化单向数据绑定的数据
        initBindData();
        serverImgs = new ArrayList<>();
    }

    //获取车辆颜色方法
    private void requestColor(){
        m.request(null).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }

                    @Override
                    public void onNext(BaseEntity entity) {
                        CarColorEntity carColorEntity = (CarColorEntity) entity;
                        colorDatas.set(carColorEntity.getColores());
                    }

                    @Override
                    public void onError(Throwable e) {
                        disDialog();
                        showMsg("车辆颜色获取失败");
                    }

                    @Override
                    public void onComplete() {
                        disDialog();
                    }
                });
    }

    //初始化单向数据绑定数据
    private void initBindData(){
        timeStr = new ObservableField<>(startStr+"-"+endStr);
        applyTimeStr = new ObservableField<>(TimeUtils.millis2String(System.currentTimeMillis(),new SimpleDateFormat("yyyy-mm-dd")));
        nameStr = new ObservableField<>(userEntity.uName);
        departmentStr = new ObservableField<>("技术部");
        colorStr = new ObservableField<>("#cccccc");
        timeStr.notifyChange();
        applyTimeStr.notifyChange();
        nameStr.notifyChange();
        departmentStr.notifyChange();
        carNumStr.notifyChange();
        colorStr.notifyChange();
    }

    //通知调用activity下的开启照相机
    private void openCamara(){
        //发eventbus消息
        EventBus.getDefault().post("开相机");
    }

    //接收拍摄的一张照片路径
    public void serveImgPath(String path){
        imgs.add(0,path);
        imgDatas.notifyChange();
    }

    //按钮点击监听器
    public class ClickListener{
        public void click(){
            //上传全部车辆照片到服务器
            uploadImgs();
        }
        public void selTimer(){

        }

    }

    private void uploadImgs(){
        imgDatas.get();
        for (Object o : imgDatas.get()){
            String str = (String) o;
            if (!str.equals("+"))
                pathes.add((String) o);
        }
        m.uploadImgs(pathes).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UploadImgsEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }
                    @Override
                    public void onNext(UploadImgsEntity uploadImgsEntity) {
                    }
                    @Override
                    public void onError(Throwable e) {
                        disDialog();
                    }

                    @Override
                    public void onComplete() {
                        disDialog();
                        //上传全部图片完成->添加车辆信息
                        //生成服务器图片地址
                        addCarInfo();
                    }
                });
    }

    //添加车辆信息方法
    private void addCarInfo(){
        Map<String,Object>map = new HashMap<>();
        map.put("carNum",carNumStr.get());
        map.put("colorId",selColorId);
        map.put("parkId",parkId);//待传参
        String jsonStr = new Gson().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsonStr);
        m.requestAddCar(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CarEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }

                    @Override
                    public void onNext(CarEntity carEntity) {
                        carId = Integer.valueOf(carEntity.getCarId());
                    }

                    @Override
                    public void onError(Throwable e) {
                        disDialog();
                    }

                    @Override
                    public void onComplete() {
                        disDialog();
                        addCarImg();
                    }
                });
    }

    //添加车辆图片方法
    private void addCarImg(){
        if (pathes.size() == 0)
            return;
        List<Map<String,Object>>list = new ArrayList<>();
        for (String str : pathes){
            Map<String,Object>map = new HashMap<>();
            map.put("carId",carId);
            map.put("imgPath",str.substring(str.lastIndexOf("/")+1));
            list.add(map);
        }
        Map<String,List>parames = new HashMap<>();
        parames.put("imgs",list);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(parames);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsonStr);
        m.requestAddCarImgs(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CarImgEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }
                    @Override
                    public void onNext(CarImgEntity carImgEntity) {
                    }
                    @Override
                    public void onError(Throwable e) {
                        disDialog();
                        showMsg(""+e.getMessage());
                    }
                    @Override
                    public void onComplete() {
                        disDialog();
                        if (!resultFlag) {
                            //提交车位信息到服务器
                            addParking();
                        }else {
                            //访客预约界面进入
                            //车辆id牌照回传会添加访客预约界面
                            Map<String,Object>map = new HashMap<>();
                            map.put("carId",carId);
                            map.put("carNum",carNumStr.get());
                            //使用eventbus将数据传递会activity，回传数据关闭界面
                            EventBus.getDefault().post(map);
                        }
//                        finishAct();
                    }
                });
    }

    //提交车位信息到服务器方法
    private void addParking(){
        Map<String,Object>map = new HashMap<>();
        map.put("parkId",parkId);
        map.put("parkUser",userEntity.uId);
        map.put("parkName",parkName);
        map.put("parkStart",""+(System.currentTimeMillis()/1000));
        map.put("parkEnd",""+(System.currentTimeMillis()/100));
        map.put("parkTime",""+(System.currentTimeMillis()/1000));
        String jsonStr = new Gson().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsonStr);
        m.requsetAddSysParking(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AddSysParkingEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                        showDialog();
                    }

                    @Override
                    public void onNext(AddSysParkingEntity addSysParkingEntity) {
                        if (addSysParkingEntity.statuesCode.equals("200")){
                            addSysParkingEntity.parkingId = parkId;
                            EventBus.getDefault().post(addSysParkingEntity);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showMsg("请求出错:"+e.getMessage());
                        disDialog();
                    }

                    @Override
                    public void onComplete() {
                        disDialog();
                        finishAct();
                    }
                });
    }

    public class ApplyParkingItemListener implements  BaseQuickAdapter.OnItemClickListener{

        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            //区分recyclerview 的 itemview点击事件
            if (adapter instanceof ColorAdapter){
                //颜色item被点击->选择对应颜色
                CarColorEntity.Values values = (CarColorEntity.Values) adapter.getItem(position);
                selColorId = values.colorId;
                colorStr.set(values.colorValue);
            }else if (adapter instanceof CarImgAdapter){
                //最后一条数据被点击->点击+->向activity发消息
                //由于服务器限制最多一个车辆只能关联6张图片
                if (imgDatas.get().size() >= 7){
                    showMsg("车辆图片最多同时选择6张");
                    return;
                }
                if (position == (imgDatas.get().size()-1)){
                    openCamara();
                }
            }
        }
    }

}
